package luanvan.app.foodnote;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONException;
import org.json.JSONObject;

import luanvan.app.foodnote.library.DatabaseHandler;
import luanvan.app.foodnote.library.UserFunctions;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class RegisterActivity extends Activity
{
	EditText inputUsername;
	EditText inputEmail;
	EditText inputPassword;
	Button btnRegister;
	Button btnRegisterEmail;
	TextView registerErrorMsg;
	
	// JSON
	private static String KEY_SUCCESS = "success";
	private static String KEY_NAME = "name";
	private static String KEY_EMAIL = "email";
	private static String KEY_UID = "uid";
	
	DatabaseHandler dbHandler;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_LEFT_ICON);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register);
		getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.add_user);
		
		inputUsername = (EditText) findViewById(R.id.registerName);
		inputEmail = (EditText) findViewById(R.id.registerEmail);
		inputPassword = (EditText) findViewById(R.id.registerPassword);
		btnRegister = (Button) findViewById(R.id.btnRegister);
		btnRegisterEmail = (Button) findViewById(R.id.btnRegisterEmail);
		registerErrorMsg = (TextView) findViewById(R.id.register_error);
		
		btnRegister.setOnClickListener(onClickListener);
		btnRegisterEmail.setOnClickListener(onClickListener);
		
		
	}
	private OnClickListener onClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btnRegister:
				/*runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						checkLogin();
					}
				});*/
					Register();
				break;
			case R.id.btnRegisterEmail:
				startActivity(new Intent(Settings.ACTION_ADD_ACCOUNT));
				break;
			}
		}

		private void Register() {
			String name = inputUsername.getText().toString();
			String email = inputEmail.getText().toString();
			String password = inputPassword.getText().toString();
			Log.d("Input Values", name + ", " + email + ", " + password);
			UserFunctions userFunction = new UserFunctions();
			if(!name.isEmpty() && !email.isEmpty() && !password.isEmpty()){
				JSONObject json = userFunction.registerUser(name, email, password);
				try {
					if(json.getString(KEY_SUCCESS) != null){
						registerErrorMsg.setText("");
						String res = json.getString(KEY_SUCCESS);
						Log.d("JSON", json.toString());
						if(Integer.parseInt(res) == 1){
							DatabaseHandler db = new DatabaseHandler(getApplicationContext());
							JSONObject json_user = json.getJSONObject("user");
							
							// Clear all previous data in database
							userFunction.logoutUser(getApplicationContext());
							db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL),
									json.getString(KEY_UID));
							
							Intent dashboard = new Intent(getApplicationContext(), MainActivity.class);
							dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							startActivity(dashboard);
							finish();
						} else {
							registerErrorMsg.setText("Đã xảy ra lỗi trong quá trình đăng kí.");
						}
					}
				} catch (JSONException e) {
	                e.printStackTrace();
	            }
			}
		}
	};

	
	@SuppressLint("NewApi")
	private void checkLogin() {
		
		/*Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
		startActivity(intent);*/
		if (inputUsername.getText().toString().isEmpty() && inputEmail.getText().toString().isEmpty()){
			TextView usernameError = (TextView) findViewById(R.id.registerName_error);
			usernameError.setText("Bạn chưa nhập tên người dùng.");
			TextView emailError = (TextView) findViewById(R.id.registerEmail_error);
			emailError.setText("Bạn chưa nhập vào email.");
		}
		else if(inputUsername.getText().toString().isEmpty()){
			TextView usernameError = (TextView) findViewById(R.id.registerName_error);
			usernameError.setText("Bạn chưa nhập tên người dùng.");
		} else if(inputEmail.getText().toString().isEmpty()){
			TextView emailError = (TextView) findViewById(R.id.registerEmail_error);
			emailError.setText("Bạn chưa nhập vào email.");
		}
		else if(!inputUsername.getText().toString().isEmpty() && !inputEmail.getText().toString().isEmpty()){
			if(!isEmailValid(inputEmail.getText().toString())){
				TextView emailError = (TextView) findViewById(R.id.registerEmail_error);
				emailError.setText("Không phải email. Vui lòng nhập lại!");
			} else {
				Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
				startActivity(intent);
			}
		}
		
	}
	/**
	 *  method is used for checking valid email id format.
	 *  @param email
	 *  @return boolean true for valid false for invalid
	 */
	public static boolean isEmailValid(String email) {
	    boolean isValid = false;

	    String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
	    CharSequence inputStr = email;

	    Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
	    Matcher matcher = pattern.matcher(inputStr);
	    if (matcher.matches()) {
	        isValid = true;
	    }
	    return isValid;
	}
}

